package com.remeberword;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by arch on 2018/3/26.
 */

public class RestoreTask extends AsyncTask<Void, Void, Integer> {

    private Context context;
    private ProgressDialog progressDialog;

    public RestoreTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("恢复中");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Integer doInBackground(Void... objects) {

        FileInputStream in = null;
        BufferedReader reader = null;
        MyDatabaseHelper dbHelper;
        SQLiteDatabase db;
        try {
            File f = Environment.getExternalStoragePublicDirectory("/Backup.txt");
            in = new FileInputStream(f);
            reader = new BufferedReader(new InputStreamReader(in));
            dbHelper = new MyDatabaseHelper(context, "WordPair.db", null);
            db = dbHelper.getWritableDatabase();

            Map<String, List> en_ch = new HashMap<>();
            Cursor cursor = db.rawQuery("select * from wordPair", new String[]{});
            if (cursor.moveToFirst()) {
                en_ch = new HashMap<>();
                do {
                    String english = cursor.getString(cursor.getColumnIndex("english"));
                    String chinese = cursor.getString(cursor.getColumnIndex("chinese"));

                    // 拆中文
                    String[] chs = chinese.split("；");
                    List<String> list = new ArrayList<>();
                    for (String s : chs)
                        list.add(s);

                    en_ch.put(english, list);
                } while (cursor.moveToNext());
            }

            String line;
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split("\t");
                String english = strs[0];
                String chinese = strs[1];

                if (en_ch.size() > 0 && en_ch.containsKey(english)) { // 单词本中有这个词
                    List<String> list = en_ch.get(english);
                    StringBuilder sb = new StringBuilder();

                    sb.append(list.get(0));
                    for (int i = 1; i < list.size(); i++)
                        sb.append("；" + list.get(i));
                    if (!list.contains(chinese)) //已有此中文解释
                        sb.append("；" + chinese);
                    chinese = sb.toString();

                    db.execSQL("update WordPair set frequency = frequency + 1, chinese = ? where english = ?",
                            new String[]{chinese, english});
                } else { // 单词本中无这个词
//                    db.execSQL("insert into wordPair (english, chinese, frequency) values(?, ?, ?)",
//                            new String[]{strs[0], strs[1], strs[2]});
                    ContentValues values = new ContentValues();
                    values.put("english", strs[0]);
                    values.put("chinese", strs[1]);
                    values.put("frequency", Integer.parseInt(strs[2]));
                    db.insert("wordPair", null, values);

                    // 拆中文
                    String[] chs = strs[1].split("；");
                    List<String> list = new ArrayList<>();
                    for (String s : chs)
                        list.add(s);

                    en_ch.put(strs[0], list);
                }
                cursor.close();
            }
            en_ch.clear();
            return 1;
//            Toast.makeText(context, "恢复完成", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            if (e instanceof FileNotFoundException)
                return 2; //找不到备份文件
            return 3;  //备份失败
//                Toast.makeText(context, "找不到备份文件", Toast.LENGTH_SHORT).show();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(Integer integer) {
        progressDialog.dismiss();
        if (integer == 1)
            Toast.makeText(context, "恢复完成", Toast.LENGTH_SHORT).show();
        else if(integer == 2)
            Toast.makeText(context, "找不到备份文件", Toast.LENGTH_SHORT).show();
        else if (integer == 3)
            Toast.makeText(context, "备份失败", Toast.LENGTH_SHORT).show();
    }
}
